package com.livra.examples.pickwebvoter.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.livra.LivraService;

@SuppressWarnings("serial")
public class AbstractPickWebVoterServlet extends HttpServlet {

    
//    private static final String LIVRA_SECRET_KEY = "e0785ad2-8314-403e-9fb8-b3b0e7e6cbc7";
//    private static final String LIVRA_CONSUMER_KEY = "5cfa980c-5c90-4473-ad1f-26b525eb4305";
    
    protected LivraService livraService = null;
    protected String currentAction = null;
    protected static final String ACTION_PARAMETER = "action";
    private static final String LIVRA_SERVICE_SESSION_ID = "LivraServiceSession";
    
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        currentAction = request.getParameter(ACTION_PARAMETER);
        if(!this.isLivraServiceCreated(request)){
            this.createLivraService(request);
        }else {
            this.retrieveFromSession(request);
        }
        super.service(request, response);
    }
    protected boolean isAction(String actionName){
        return actionName !=null && actionName.equalsIgnoreCase(currentAction);
    }
//    protected void addLivraServiceOauthClient() {
//        livraService.createOAuthClient(LIVRA_CONSUMER_KEY, LIVRA_SECRET_KEY);
//        
//    }
    
    private void retrieveFromSession(HttpServletRequest request) {
        this.livraService = (LivraService) request.getSession().getAttribute(LIVRA_SERVICE_SESSION_ID);
    }

    private void createLivraService(HttpServletRequest request) {
        this.livraService = new LivraService();
        request.getSession().setAttribute(LIVRA_SERVICE_SESSION_ID, this.livraService);
    }
    
    private boolean isLivraServiceCreated(HttpServletRequest request) {
        return request.getSession().getAttribute(LIVRA_SERVICE_SESSION_ID) != null;
    }
    
}
